All files / app/api/posts/[id]/comments route.ts

0% Statements 0/40
0% Branches 0/20
0% Functions 0/2
0% Lines 0/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131                                                                                                                                                                                                                                                                     
import { NextRequest, NextResponse } from "next/server";
import { connectDB } from "@/lib/mongodb";
import { requireAuth } from "@/lib/session";
import Comment from "@/models/Comment";
import Post from "@/models/Post";
 
type Params = Promise<{ id: string }>;
 
// GET /api/posts/[id]/comments - List comments for a post
export async function GET(
  request: NextRequest,
  { params }: { params: Params }
) {
  try {
    await requireAuth();
    await connectDB();
 
    const { id: postId } = await params;
 
    // Check if post exists
    const post = await Post.findById(postId);
    if (!post || post.deletedAt) {
      return NextResponse.json(
        { error: { code: "NOT_FOUND", message: "Post not found" } },
        { status: 404 }
      );
    }
 
    const comments = await Comment.find({ postId })
      .sort({ createdAt: 1 })
      .populate("authorId", "name email image");
 
    return NextResponse.json({ data: comments });
  } catch (error) {
    if (error instanceof Error && error.message === "Unauthorized") {
      return NextResponse.json(
        { error: { code: "UNAUTHORIZED", message: "Authentication required" } },
        { status: 401 }
      );
    }
    console.error("Error fetching comments:", error);
    return NextResponse.json(
      {
        error: {
          code: "INTERNAL_ERROR",
          message: "Failed to fetch comments",
        },
      },
      { status: 500 }
    );
  }
}
 
// POST /api/posts/[id]/comments - Add a comment
export async function POST(
  request: NextRequest,
  { params }: { params: Params }
) {
  try {
    const session = await requireAuth();
    await connectDB();
 
    const { id: postId } = await params;
    const body = await request.json();
    const { body: commentBody } = body;
 
    if (!commentBody) {
      return NextResponse.json(
        {
          error: {
            code: "VALIDATION_ERROR",
            message: "Comment body is required",
          },
        },
        { status: 400 }
      );
    }
 
    // Check if post exists and allows comments
    const post = await Post.findById(postId);
    if (!post || post.deletedAt) {
      return NextResponse.json(
        { error: { code: "NOT_FOUND", message: "Post not found" } },
        { status: 404 }
      );
    }
 
    if (!post.allowComments) {
      return NextResponse.json(
        {
          error: {
            code: "COMMENTS_DISABLED",
            message: "Comments are disabled for this post",
          },
        },
        { status: 403 }
      );
    }
 
    const comment = await Comment.create({
      postId,
      authorId: session.user.id,
      body: commentBody,
    });
 
    const populatedComment = await Comment.findById(comment._id).populate(
      "authorId",
      "name email image"
    );
 
    return NextResponse.json({ data: populatedComment }, { status: 201 });
  } catch (error) {
    if (error instanceof Error && error.message === "Unauthorized") {
      return NextResponse.json(
        { error: { code: "UNAUTHORIZED", message: "Authentication required" } },
        { status: 401 }
      );
    }
    console.error("Error creating comment:", error);
    return NextResponse.json(
      {
        error: {
          code: "INTERNAL_ERROR",
          message: "Failed to create comment",
        },
      },
      { status: 500 }
    );
  }
}